import locker from './lock'
const getKey = (codeType, condition) => {
    let key = codeType;

    if (condition) {
        for (let p in condition) {
            key += "_" + p + "_" + (condition[p] || '');
        }
    }
    // console.log("cache key : ",key);
    return key;
}
//code provider
const codeProvider = {


    registerCodeType(codeType, condition) {

        return new Promise((resolve, reject) => {
            let key = getKey('code_' + codeType, condition);
            let codeData = _g.getCacheData(key);
            codeData = codeData ? codeData.data : null;
            if (codeData) {
                resolve(codeData);
                return;
            }

            locker.lock(key, () => {
                let codeData = _g.getCacheData(key);
                codeData = codeData ? codeData.data : null;
                if (codeData) {
                    resolve(codeData);
                    locker.releaseLock(key);//release lock
                    return;
                }
                // _g.putCacheData(key,{requestState:true,reqCount:0});
                console.log(codeType, 'req from server!');
                this._getCodeList(codeType, condition).then(resp => {
                    //   console.log('resp=>',resp);
                    if (resp) {
                        let cacheTimeout = resp.cacheTimeout || 0;
                        if (cacheTimeout) {
                            _g.putCacheData(getKey('code_' + codeType, condition), { data: resp, requestState: false }, parseInt(cacheTimeout));
                        } else {
                            _g.putCacheData(getKey('code_' + codeType, condition), { data: resp, requestState: false });
                        }
                    }
                    locker.releaseLock(key);
                    resolve(resp);
                    return;
                }).catch(error=>{
                    
                    locker.releaseLock(key);
                    reject(error);
                });;
                return;
            });

            return;
        });

    },
    _getCodeList(codeType, condition) {
        return new Promise((resolve, reject) => {
            const _data = {
                params: {
                    codeType: codeType
                }
            };
            Object.assign(_data.params, condition);

            axios.get('code/getCodeList', _data).then((response) => {

                resolve(response.data.data)
            }, (response) => {
                reject(response)
                _g.closeGlobalLoading()
                _g.toastMsg('warning', '请求超时，请检查网络');
            }).catch(error => {
                console.error(error);
                reject(error);
            });

        });

    },

    getName(codeType, value, condition = {}) {
        return new Promise((resolve, reject) => {
            let codeData = _g.getCacheData(getKey('code_' + codeType, condition));
            //   console.log(store.state.cacheData);
            codeData = codeData ? codeData.data : null;
            //   console.log('codeData',codeData);
            // console.log('value',value);
            let result = value;
            if (!codeData) {
                this.registerCodeType(codeType, condition).then(resp => {
                    let codeList = resp.codeList;
                    let textField = resp.textField || 'text';
                    let valueField = resp.valueField || 'value';

                    result = _.filter(codeList, item => { return item[valueField] == value; });
                    result = result ? (result[0] ? result[0][textField] : value) : value;
                    resolve(result);
                });
                return;
            }
            let codeList = codeData.codeList;
            let textField = codeData.textField || 'text';
            let valueField = codeData.valueField || 'value';

            result = _.filter(codeList, item => {return item[valueField] == value; });
            result = result ? (result[0] ? result[0][textField] : value) : value;
            resolve(result);
            return;
        });


    },

    parseData(codeData) {//if tree return tree ,if seq return list;
        if(!codeData) return;
        let seqType = codeData.seqType;
        let result = [];
        if (seqType == 'tree' || seqType == 'tree_pojo') {//树类型
            return codeData;
        } else {
            let codeList = codeData.codeList;
            let textField = codeData.textField || 'text';
            let valueField = codeData.valueField || 'value';
            result = _.map(codeList || [], item => { return { text: item[textField], value: item[valueField], other: item } });
            return result;
        }
    },
    getList(codeType, condition = {}) {

        return new Promise((resolve, reject) => {
            let codeData = _g.getCacheData(getKey('code_' + codeType, condition));
            codeData = codeData ? codeData.data : null;
            let result = null;
            // console.log("param->",condition,codeData);
            if (!codeData) {

                this.registerCodeType(codeType, condition).then(resp => {
                    // let codeList = resp.codeList;
                    // let textField = resp.textField || 'text';
                    // let valueField = resp.valueField || 'value';
                    // result =  _.map(codeList||[],item=>{return {text:item[textField],value:item[valueField],other:item}});
                    result = this.parseData(resp);
                    resolve(result);
                });
                return;
            }
            // let codeList = codeData.codeList;
            // let textField = codeData.textField || 'text';
            // let valueField = codeData.valueField || 'value';
            // result =  _.map(codeList||[],item=>{return {text:item[textField],value:item[valueField],other:item}});
            result = this.parseData(codeData);
            // console.log('codeResult->',result);
            resolve(result);
            return;

        });

    },
    getValue(codeType, name, condition = {}) {
        return new Promise((resolve, reject) => {
            let codeData = _g.getCacheData(getKey('code_' + codeType, condition));
            codeData = codeData ? codeData.data : null;
            console.log('codeData->',codeData);
            let result = null;
            if (!codeData) {
                this.registerCodeType(codeType, condition).then(resp => {
                    let codeList = resp.codeList;
                    let textField = resp.textField || 'text';
                    let valueField = resp.valueField || 'value';
                    result = _.filter(codeList || [], item => { return item[textField] == name; });
                    result = result ? (result[0] ? result[0][textField] : name) : name;
                    resolve(result);
                });
                return;
            }
            let codeList = codeData.codeList;
            let textField = codeData.textField || 'text';
            let valueField = codeData.valueField || 'value';
            result = _.filter(codeList || [], item => { return item[textField] == name; });
            result = result ? (result[0] ? result[0][textField] : name) : name;
            resolve(result);
            return;

        });

    },
    getItem(codeType, value, condition = {}) {
        return new Promise((resolve, reject) => {
            let codeData = _g.getCacheData(getKey('code_' + codeType, condition));
            codeData = codeData ? codeData.data : null;
            if (!codeData) {
                this.registerCodeType(codeType, condition).then(resp => {
                    let codeList = resp.codeList;
                    let textField = resp.textField || 'text';
                    let valueField = resp.valueField || 'value';
                    result = _.filter(codeList, item => { return item[valueField] == value; });
                    result = result ? result[0] : value;
                    resolve(result);
                });
                return;
            }
            let codeList = codeData.codeList;
            let textField = codeData.textField || 'text';
            let valueField = codeData.valueField || 'value';
            result = _.filter(codeList, item => { return item[valueField] == value; });
            result = result ? result[0] : value;
            resolve(result);
            return;
        });

    }
}
const unitProvider = {
    registerUnit(unitName, condition) {
        
        return new Promise((resolve, reject) => {
            let key = getKey('unit_' + unitName, condition);
            let codeData = _g.getCacheData(key);
            codeData = codeData ? codeData.data : null;

          
            if (codeData) {
                resolve(codeData);
                return;
            }
            locker.lock(key, () => {

                let codeData = _g.getCacheData(key);
                codeData = codeData ? codeData.data : null;
    
                if (codeData) {
                    resolve(codeData);
                    locker.releaseLock(key);//release lock
                    return;
                }
                // _g.putCacheData(key,{requestState:true,reqCount:0});
                console.log(unitName, 'req from server!');
                this._getUnitDefine(unitName, condition).then(resp => {
                    //   console.log('resp=>',resp);
                    if (resp && resp.data) {
                        _g.putCacheData(getKey('unit_' + unitName, condition), { data: resp, requestState: false }, 30000);
                    }
                    locker.releaseLock(key);
                    resolve(resp);
                    return;
                }).catch(error=>{
                    locker.releaseLock(key);
                    reject(error);
                });
                return;
            });

            return;
        });

    },
    _getUnitDefine(unitName, condition) {

        return new Promise((resolve, reject) => {
            const _data = {
                params: {
                    unitName: unitName
                }
            };

        
            Object.assign(_data.params, condition);
        
            axios.get('unit/ins/getUnit', _data).then((response) => {

                if(response && response.data.code === 200){

                    resolve(response.data.data)
                }else{
                    if(response.data.msg){
                        _g.toastMsg('error', response.data.msg);
                    }
                    reject(response);
                }
            }, (response) => {
                reject(response)
                _g.closeGlobalLoading()
                _g.toastMsg('warning', '请求超时，请检查网络');
            }).catch(error => {
                console.error(error);
                reject(error);
            });

        });

    },
    loadUnitDefine(unitName, condition) {
        return new Promise((resolve, reject) => {
         
            let unitDefine = _g.getCacheData(getKey('unit_' + unitName, condition));
            unitDefine = unitDefine ? unitDefine.data : null;
            
            if (!unitDefine) {
                
                this.registerUnit(unitName, condition).then(resp => {
                   
                    resolve(resp);
                });
                return;
            }
            resolve(unitDefine);
            return;

        });

    },
}
export {
    codeProvider,
    unitProvider
}